package com.yugao.fintech.antelope.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yugao.fintech.antelope.base.model.constants.TreeCons;
import com.yugao.fintech.antelope.shop.assembly.GoodsCategoryAssembly;
import com.yugao.fintech.antelope.shop.mapper.GoodsCategoryMapper;
import com.yugao.fintech.antelope.shop.model.entity.GoodsCategory;
import com.yugao.fintech.antelope.shop.service.GoodsCategoryService;
import com.yugao.fintech.framework.assistant.utils.exception.BizException;
import com.yugao.fintech.framework.assistant.utils.tree.TreeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品分类
 */
@Slf4j
@Service
public class GoodsCategoryServiceImpl extends ServiceImpl<GoodsCategoryMapper, GoodsCategory>
    implements IService<GoodsCategory>, GoodsCategoryService {
    @Autowired
    private GoodsCategoryAssembly categoryAssembly;
    
    @Override
    public List<GoodsCategoryResp> listCategory() {
    	return this.list().stream()
    	        .map(categoryAssembly::toCategoryResp).collect(Collectors.toList());
    }

    @Override
    public GoodsCategoryResp getCategory(Long id) {
        GoodsCategory entity = this.getById(id);
    	return categoryAssembly.toCategoryResp(entity);
    }

    @Override
    public boolean saveCategory(GoodsCategorySaveReq req) {
        GoodsCategory entity = categoryAssembly.toCategory(req);
    	return this.save(entity);
    }

    @Override
    public boolean updateCategory(GoodsCategoryUpdateReq req) {
        GoodsCategory entity = categoryAssembly.toCategory(req);
        if (Objects.equals(entity.getId(), entity.getParentId())) {
            throw new BizException("上级不能选择自己");
        }
    	return this.updateById(entity);
    }

    @Override
    public boolean deleteCategory(Long id) {
    	return this.removeById(id);
    }
    
    @Override
    public boolean batchDeleteCategory(List<Long> ids) {
    	return this.removeByIds(ids);
    }

    @Override
    public List<GoodsCategoryTreeResp> listCategoryTree(GoodsCategoryTreeReq req) {
        List<GoodsCategoryTreeResp> flatList = this.list().stream().map(categoryAssembly::toCategoryTreeResp)
                .collect(Collectors.toList());
        List<GoodsCategoryTreeResp> treeList = TreeUtils.build(flatList, TreeCons.ROOT_PARENT_ID);
        TreeUtils.filter(treeList, e -> StringUtils.isEmpty(req.getName()) || e.getName().contains(req.getName()) );
        return treeList;
    }
}
